package service

import (
	"gin/common"
	"gin/model"
	nlpWord "gin/tai/dict/word"
	"gin/validate"
)

func CreateWordSimilar(Data validate.AddWordSimilar) (WordSimilarModel model.WordSimilar, err error) {
	WordSimilarModel.Word = Data.Word
	WordSimilarModel.SourceWord = Data.SourceWord

	_, err = WordSimilarModel.Insert()
	return
}

func FindWordSimilar(Param common.SelectQueryParam) (resData model.WordSimilar, err error) {
	var logModel model.WordSimilar

	resData, err = logModel.Find(Param)

	return
}

func SelectWordSimilar(Param common.SelectQueryParam) (total int64, resData []model.WordSimilar, err error) {
	var logModel model.WordSimilar

	total, resData, err = logModel.Select(Param)

	return
}

func UpdateWordSimilar(Data validate.UpdateWordSimilar) (resData model.WordSimilar, err error) {
	resData, err = resData.Update(model.WordSimilar{
		Id:         Data.Id,
		Word:       Data.Word,
		SourceWord: Data.SourceWord,
	})
	return
}

// 删除段落词语
func DeleteWordSimilar(param *common.Filter) {

	var logModel model.WordSimilar
	logModel.DeleteByFilter(param)
	return
}

func QueryWordSimilarSimilarWords(param *validate.QuerySimilarWordWithAnalysis) (total int64, rows []model.WordSimilar, err error) {
	if &param.Number == nil {
		param.Number = 20
	}
	var wordModel model.Word
	existRecord, err := wordModel.Find(common.SelectQueryParam{
		Fields: "*",
		Limit:  1,
		Offset: 0,
		Order:  "id desc",
		Filter: common.Filter{Filter: map[string]interface{}{
			"-eq": map[string]interface{}{
				"condition": "word = ?",
				"val":       param.Word,
			},
		},
		},
	})

	// 没有保存过该词语的就写入
	if err != nil || existRecord.Id <= 0 {
		res, err := nlpWord.Similar(param.Word, param.Number)
		if err != nil {
			return total, rows, err
		}
		wordModel.Word = param.Word
		id, err := wordModel.Insert()
		if err != nil {
			return total, rows, err
		}
		var similarModel model.WordSimilar
		similarLength := len(res.Response.SimilarWords)
		similarWordModels := make([]model.WordSimilar, similarLength)

		for index, similarWord := range res.Response.SimilarWords {
			similarWordModels[index].Word = *similarWord
			similarWordModels[index].WordId = id
			similarWordModels[index].SourceWord = param.Word
		}
		similarModel.InsertAll(&similarWordModels)

		if uint64(similarLength) > param.Number {
			similarWordModels = similarWordModels[:param.Number-1]
		}
		return int64(similarLength), similarWordModels, err
	} else {
		return SelectWordSimilar(common.SelectQueryParam{
			Fields: "*",
			Limit:  int(param.Number),
			Offset: 0,
			Order:  "id desc",
			Filter: common.Filter{Filter: map[string]interface{}{
				"-eq": map[string]interface{}{
					"condition": "word_id = ?",
					"val":       existRecord.Id,
				},
			}},
		})
	}

}
